<?php
/**
 * Created by PhpStorm.
 * User: beijingwhg
 * Date: 2017/5/10
 * Time: 下午12:05
 */

function admin () {
    return \Illuminate\Support\Facades\Auth::guard('admin')->user();
}

function user() {
    if (session('isAdmin')) {
        return admin();
    }

    return \Illuminate\Support\Facades\Auth::guard('user')->user();
}

function manageMenu () {
    $myPowers = getMyPower();

    $powers = getPowers();

    $menu = [];

    foreach ($myPowers as $myPower=>$details) {
        $power = $powers->find($myPower);

        $key = $power->power_key;

        $active = '';

        if ($key == getRoute()) {
            $active = 'active';
        }

        $menu[] = [
            'url'    => url('/admin/'.$key),
            'key'    => $power->power_key,
            'name'   => $power->power_name,
            'active' => $active,
            'icon'   => $power->icon,
        ];
    }
    return $menu;
}

function getPowers ($refresh = false) {
    if (!$refresh && \Illuminate\Support\Facades\Cache::has('powers')) {
        return \Illuminate\Support\Facades\Cache::get('powers');
    }

    $powers = \App\Models\PowerModel::orderBy('sort')->get();

    \Illuminate\Support\Facades\Cache::put('powers', $powers, 86400);

    return $powers;
}

function getPowersArray () {
    $powersToArray = [];
    foreach (getPowers() as $power) {
        $powersToArray[$power->power_id] = $power;
    }
    return $powersToArray;
}

function getMyPower () {
    return json_decode(getRole()->power_ids, true);
}

function needPower ($route) {
    return getPowers()->where('power_key', $route)->first();
}

function ifPermit ($route) {
    return key_exists(needPower($route)->power_id, getPowersArray());
}

function getRole () {
    if (!$role = session('role')) {
        $role = \App\Models\RoleModel::find(admin()->role_id);

        session('role', $role);
    }
    return $role;
}

function url2Route ($url) {
    if (substr($url, -1) != '/') {
        $url .= '/';
    }
    preg_match('@\/admin\/(.*?)\/@is', $url, $route);

    if ($route) {
        return strtolower($route[1]);
    } else {
        return false;
    }
}

function getRoute () {
    return url2Route($_SERVER['REQUEST_URI']);
}